package org.luxor.commons.core.utils;

import org.luxor.commons.core.constant.OsType;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 获取操作系统类型相关信息
 *
 * @author YanXinMing @date 2024/9/6
 */
public class SystemUtils {
    private static final String OS_NAME = "os.name";
    private static final String OS_VERSION = "os.version";

    /**
     * Returns type of operating system.
     */
    public static OsType getOsType() throws SecurityException {
        String osName = getOsName();
        if (osName != null) {
            if (osName.contains("Windows")) {
                return OsType.WINDOWS;
            }
            if (osName.contains("Linux")) {
                return OsType.LINUX;
            }
            if (osName.contains("Solaris") || osName.contains("SunOS")) {
                return OsType.SOLARIS;
            }
            if (osName.contains("OS X")) {
                return OsType.MACOSX;
            }
            // determine another OS here
        }
        return OsType.UNKNOWN;
    }

    /**
     * judge os is Windows
     *
     * @return true：is windows  false：another
     */
    public static boolean isWindows() {
        String osName = getOsName();
        return osName != null && osName.startsWith("Windows");
    }

    /**
     * judge os is mac
     *
     * @return true：is mac  false：another
     */
    public static boolean isMacOs() {
        String osName = getOsName();
        return osName != null && osName.startsWith("Mac");
    }

    /**
     * judge os is Linux
     *
     * @return true：is linux  false：another
     */
    public static boolean isLinux() {
        String osName = getOsName();
        return (osName != null && osName.startsWith("Linux")) || (!isWindows() && !isMacOs());
    }

    /**
     * get os name
     *
     * @return os.name
     */
    public static String getOsName() {
        return System.getProperty(OS_NAME);
    }

    /**
     * get one PATH by key
     */
    public static String getEnv(String key) {
        return System.getenv(key);
    }

    /**
     * get env PATH
     */
    public static List<String> getPath() {
        String sep = File.pathSeparator;
        String paths = System.getenv("PATH");
        return new ArrayList<>(Arrays.asList(paths.split(sep)));
    }
}
